import logging
import logging.config
from os import path, makedirs
import signal
from yaml import safe_load
from time import sleep
from threading import Event
from rs485tomqtt.comm_service import CommService
from .mqtt_client import MqttClient
import asyncio

_log = None


class GatewayHost:
    def __init__(self, config_file: str = None) -> None:
        signal.signal(signal.SIGINT, lambda _, __: self.stop())
        if config_file is None:
            config_file = path.dirname(path.dirname(path.abspath(
                __file__))) + '/config/rs485tomqtt.yaml'.replace('/', path.sep)
        # 该项目路径
        self.filePath = path.dirname(path.dirname(
            path.abspath(config_file))).replace('/', path.sep) + path.sep
        with open(config_file, encoding="utf-8") as general_config:
            self._config = safe_load(general_config)

        # 创建logs文件夹
        log_dir = path.join(self.filePath, "logs")
        makedirs(log_dir, exist_ok=True)
        logging.config.fileConfig(
            self.filePath + "logs.conf", disable_existing_loggers=False)

        global _log
        _log = logging.getLogger('service')

        self.mqtt = MqttClient(self._config["mqtt"])
        self.commSerial = CommService(
            self.filePath, self._config["rs485"], self.mqtt)

    def start(self) -> bool:
        _log.info("485程序开始运行...")
        self.mqtt.start()
        asyncio.run(self.commSerial.start())

    def stop(self) -> None:
        asyncio.create_task(self.commSerial.stop())
        _log.info("485程序停止运行...")
